"""
AI Prompts Management Models
AI提示词管理数据模型
"""
from django.db import models
from django.contrib.auth import get_user_model
from django.utils import timezone
import json
import uuid

User = get_user_model()

class CustomPromptTemplate(models.Model):
    """自定义提示词模板模型"""

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    name = models.CharField(max_length=200, verbose_name='模板名称')
    description = models.TextField(verbose_name='模板描述')
    template_id = models.CharField(max_length=100, unique=True, verbose_name='模板ID')
    prompt_type = models.CharField(
        max_length=50,
        choices=[
            ('question_generation', '题目生成'),
            ('grading', '评分'),
            ('analytics', '分析'),
            ('cheating_detection', '作弊检测'),
            ('adaptive_learning', '自适应学习'),
            ('content_moderation', '内容审核'),
            ('feedback_generation', '反馈生成'),
            ('study_recommendation', '学习建议'),
        ],
        verbose_name='提示词类型'
    )
    subject = models.CharField(
        max_length=50,
        choices=[
            ('math', '数学'),
            ('chinese', '语文'),
            ('english', '英语'),
            ('science', '科学'),
            ('physics', '物理'),
            ('chemistry', '化学'),
            ('biology', '生物'),
            ('history', '历史'),
            ('geography', '地理'),
            ('politics', '政治'),
            ('general', '通用'),
        ],
        default='general',
        verbose_name='学科'
    )
    difficulty = models.CharField(
        max_length=20,
        choices=[
            ('easy', '简单'),
            ('medium', '中等'),
            ('hard', '困难'),
            ('advanced', '高级'),
        ],
        default='medium',
        verbose_name='难度级别'
    )
    template_content = models.TextField(verbose_name='模板内容')
    variables = models.JSONField(
        default=list,
        verbose_name='模板变量',
        help_text='模板中使用的变量列表'
    )
    examples = models.JSONField(
        default=list,
        verbose_name='使用示例',
        help_text='模板的使用示例'
    )
    version = models.CharField(max_length=20, default='1.0', verbose_name='版本号')
    is_active = models.BooleanField(default=True, verbose_name='是否启用')
    is_public = models.BooleanField(default=False, verbose_name='是否公开')

    # 创建者和修改信息
    created_by = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        related_name='created_prompts',
        verbose_name='创建者'
    )
    modified_by = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        related_name='modified_prompts',
        verbose_name='修改者',
        null=True,
        blank=True
    )

    # 时间戳
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')

    # 元数据
    metadata = models.JSONField(
        default=dict,
        verbose_name='元数据',
        blank=True,
        help_text='额外的模板信息'
    )

    # 统计信息
    usage_count = models.IntegerField(default=0, verbose_name='使用次数')
    success_count = models.IntegerField(default=0, verbose_name='成功次数')
    error_count = models.IntegerField(default=0, verbose_name='错误次数')

    class Meta:
        db_table = 'ai_prompt_templates'
        verbose_name = '提示词模板'
        verbose_name_plural = '提示词模板'
        ordering = ['-created_at']
        indexes = [
            models.Index(fields=['template_id', 'is_active']),
            models.Index(fields=['prompt_type', 'subject']),
            models.Index(fields=['created_by', 'is_active']),
            models.Index(fields=['is_public', 'is_active']),
        ]

    def __str__(self):
        return f"{self.name} ({self.template_id})"

    def increment_usage(self, success=True):
        """增加使用统计"""
        self.usage_count += 1
        if success:
            self.success_count += 1
        else:
            self.error_count += 1
        self.save(update_fields=['usage_count', 'success_count', 'error_count'])

    def get_success_rate(self):
        """获取成功率"""
        if self.usage_count == 0:
            return 0
        return (self.success_count / self.usage_count) * 100

class PromptUsageLog(models.Model):
    """提示词使用日志模型"""

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    template = models.ForeignKey(
        CustomPromptTemplate,
        on_delete=models.CASCADE,
        related_name='usage_logs',
        verbose_name='使用的模板'
    )
    user = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        related_name='prompt_usage_logs',
        verbose_name='使用用户'
    )

    # 使用信息
    variables_used = models.JSONField(verbose_name='使用的变量')
    rendered_prompt = models.TextField(verbose_name='渲染后的提示词')
    prompt_length = models.IntegerField(verbose_name='提示词长度')

    # AI响应信息
    ai_response = models.TextField(verbose_name='AI响应', blank=True)
    response_time = models.FloatField(verbose_name='响应时间（秒）')
    token_usage = models.JSONField(
        default=dict,
        verbose_name='Token使用情况',
        blank=True
    )

    # 结果状态
    is_success = models.BooleanField(verbose_name='是否成功')
    error_message = models.TextField(verbose_name='错误信息', blank=True)

    # 时间戳
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='使用时间')

    # 上下文信息
    context_type = models.CharField(
        max_length=50,
        choices=[
            ('question_generation', '题目生成'),
            ('grading', '评分'),
            ('analytics', '分析'),
            ('other', '其他'),
        ],
        verbose_name='上下文类型'
    )
    context_id = models.CharField(max_length=100, verbose_name='上下文ID', blank=True)

    class Meta:
        db_table = 'ai_prompt_usage_logs'
        verbose_name = '提示词使用日志'
        verbose_name_plural = '提示词使用日志'
        ordering = ['-created_at']
        indexes = [
            models.Index(fields=['template', 'created_at']),
            models.Index(fields=['user', 'created_at']),
            models.Index(fields=['is_success', 'created_at']),
            models.Index(fields=['context_type', 'context_id']),
        ]

    def __str__(self):
        return f"{self.template.name} - {self.user.username} - {self.created_at}"

class PromptTemplateVersion(models.Model):
    """提示词模板版本历史模型"""

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    template = models.ForeignKey(
        CustomPromptTemplate,
        on_delete=models.CASCADE,
        related_name='version_history',
        verbose_name='主模板'
    )
    version_number = models.CharField(max_length=20, verbose_name='版本号')

    # 版本快照
    name_snapshot = models.CharField(max_length=200, verbose_name='名称快照')
    description_snapshot = models.TextField(verbose_name='描述快照')
    template_content_snapshot = models.TextField(verbose_name='模板内容快照')
    variables_snapshot = models.JSONField(verbose_name='变量快照')
    examples_snapshot = models.JSONField(verbose_name='示例快照')
    metadata_snapshot = models.JSONField(verbose_name='元数据快照')

    # 版本信息
    created_by = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        related_name='created_template_versions',
        verbose_name='创建者'
    )
    change_reason = models.TextField(verbose_name='变更原因', blank=True)
    is_major_version = models.BooleanField(default=False, verbose_name='是否主要版本')

    # 时间戳
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='创建时间')

    class Meta:
        db_table = 'ai_prompt_template_versions'
        verbose_name = '提示词模板版本'
        verbose_name_plural = '提示词模板版本'
        ordering = ['-created_at']
        unique_together = ['template', 'version_number']
        indexes = [
            models.Index(fields=['template', 'created_at']),
            models.Index(fields=['created_by', 'created_at']),
        ]

    def __str__(self):
        return f"{self.template.name} v{self.version_number}"

class PromptTemplateReview(models.Model):
    """提示词模板评审模型"""

    id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
    template = models.ForeignKey(
        CustomPromptTemplate,
        on_delete=models.CASCADE,
        related_name='reviews',
        verbose_name='评审的模板'
    )
    reviewer = models.ForeignKey(
        User,
        on_delete=models.CASCADE,
        related_name='prompt_reviews',
        verbose_name='评审者'
    )

    # 评审结果
    rating = models.IntegerField(
        choices=[
            (1, '1星 - 很差'),
            (2, '2星 - 较差'),
            (3, '3星 - 一般'),
            (4, '4星 - 良好'),
            (5, '5星 - 优秀'),
        ],
        verbose_name='评分'
    )
    review_comment = models.TextField(verbose_name='评审意见')

    # 评审维度
    clarity_score = models.IntegerField(
        default=3,
        verbose_name='清晰度评分',
        help_text='提示词表达是否清晰明了'
    )
    effectiveness_score = models.IntegerField(
        default=3,
        verbose_name='有效性评分',
        help_text='提示词是否能产生预期效果'
    )
    completeness_score = models.IntegerField(
        default=3,
        verbose_name='完整性评分',
        help_text='提示词是否包含必要的指导信息'
    )

    # 评审状态
    is_approved = models.BooleanField(default=True, verbose_name='是否通过评审')
    is_public_review = models.BooleanField(default=True, verbose_name='是否公开评审')

    # 时间戳
    created_at = models.DateTimeField(auto_now_add=True, verbose_name='评审时间')
    updated_at = models.DateTimeField(auto_now=True, verbose_name='更新时间')

    class Meta:
        db_table = 'ai_prompt_template_reviews'
        verbose_name = '提示词模板评审'
        verbose_name_plural = '提示词模板评审'
        ordering = ['-created_at']
        unique_together = ['template', 'reviewer']
        indexes = [
            models.Index(fields=['template', 'is_approved']),
            models.Index(fields=['reviewer', 'created_at']),
            models.Index(fields=['rating', 'created_at']),
        ]

    def __str__(self):
        return f"{self.template.name} - {self.reviewer.username} ({self.rating}星)"

    def get_average_score(self):
        """获取平均评分"""
        return (self.clarity_score + self.effectiveness_score + self.completeness_score) / 3